package pers.xx.sbm;


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ConvertVideoReduce {

    private final static String inputPath = "E:\\课件\\已完结课程（mp4、flv格式）\\传统文化与现代经营管理\\{1}--课程\\{1}--第1章传统文化概述";

    private final static String outputPath = "C:\\Users\\18359\\Desktop\\test\\";

    private final static String ffmpegPath = "F:\\ffmpeg-N-100991-gd8181cbbc4-win64-gpl-shared\\bin\\";

    public static void main(String args[]) throws IOException {
        File file = new File(inputPath);
        if (!file.isDirectory()) {
            System.out.println("请使用有效的输入文件夹");
            return;
        }
        if (!isDirectory(outputPath)) {
            System.out.println("请使用有效的输出文件夹");
            return;
        }
        File[] files = file.listFiles();
        dealDirectory(files);
    }


    /**
     * @description 处理文件夹
     * @author XieXing
     * @date 2021/2/7 11:17
     */
    public static void dealDirectory(File[] files) {
        for (File tmp : files) {
            if (tmp.isFile()) {
                String curPath = tmp.getAbsolutePath();
                if (process(curPath)) {
                    System.out.println(tmp.getName() + "转换成功!");
                }
            }
            if (tmp.isDirectory()) {
                dealDirectory(tmp.listFiles());
            }
        }
    }


    /**
     * @description 将文件转换成mp4
     * @author XieXing
     * @date 2021/2/7 11:33
     */
    public static boolean process(String filePath) {
        int type = checkContentType(filePath);
        boolean status = false;
        status = processMp4(filePath);// 直接转成mp4格式
        return status;
    }

    /**
     * @description 判断是否是文件夹
     * @author XieXing
     * @date 2021/2/7 11:49
     */
    public static boolean isDirectory(String path) {
        File file = new File(path);
        return file.isDirectory();
    }

    private static int checkContentType(String filePath) {
        String type = filePath.substring(filePath.lastIndexOf(".") + 1, filePath.length())
                .toLowerCase();
        // ffmpeg能解析的格式：（asx，asf，mpg，wmv，3gp，mp4，mov，avi，flv等）
        if (type.equals("avi")) {
            return 0;
        } else if (type.equals("mpg")) {
            return 0;
        } else if (type.equals("wmv")) {
            return 0;
        } else if (type.equals("3gp")) {
            return 0;
        } else if (type.equals("mov")) {
            return 0;
        } else if (type.equals("mp4")) {
            return 0;
        } else if (type.equals("asf")) {
            return 0;
        } else if (type.equals("asx")) {
            return 0;
        } else if (type.equals("flv")) {
            return 0;
        }
        // 对ffmpeg无法解析的文件格式(wmv9，rm，rmvb等),
        // 可以先用别的工具（mencoder）转换为avi(ffmpeg能解析的)格式.
        else if (type.equals("wmv9")) {
            return 1;
        } else if (type.equals("rm")) {
            return 1;
        } else if (type.equals("rmvb")) {
            return 1;
        }
        return 9;
    }

    private static boolean processMp4(String filePath) {
        String newFileName = filePath.substring(filePath.lastIndexOf("\\") + 1);//获取文件名
        newFileName = newFileName.substring(0, newFileName.lastIndexOf(".")) + ".mp4";//替换后缀
        List<String> command = new ArrayList<String>();
        command.add(ffmpegPath + "ffmpeg");
        command.add("-i");
        command.add(filePath);
        command.add("-c:v");
        command.add("libx264");
        command.add("-mbd");
        command.add("0");
        command.add("-c:a");
        command.add("aac");
        command.add("-strict");
        command.add("-2");
        command.add("-pix_fmt");
        command.add("yuv420p");
        command.add("-movflags");
        command.add("faststart");
        command.add(outputPath + newFileName);
        try {

            Process videoProcess = new ProcessBuilder(command).redirectErrorStream(true).start();

            new PrintStreamReduce(videoProcess.getErrorStream()).start();

            new PrintStreamReduce(videoProcess.getInputStream()).start();

            videoProcess.waitFor();

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}

class PrintStreamReduce extends Thread {
    java.io.InputStream __is = null;

    public PrintStreamReduce(java.io.InputStream is) {
        __is = is;
    }

    public void run() {
        try {
            while (this != null) {
                int _ch = __is.read();
                if (_ch != -1)
                    System.out.print((char) _ch);
                else break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}